package com.yuantu.judiciary.utils.ip;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuantu.judiciary.config.DefaultConfig;
import com.yuantu.judiciary.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
public class AddressUtil {
    private static final Logger log = LoggerFactory.getLogger(AddressUtil.class);

    /**
     * IP地址查询
     * */
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    /**
     * 未知地址
     */
    public static final String UNKNOWN = "XX XX";
    /**
     * 默认地址
     */
    public static final String DEFAULT = "内网IP";


    public static String getRealAddressByIP(String ip) {
        // 内网不查询
        if (IpUtil.internalIp(ip)) {
            return DEFAULT;
        }
        if (DefaultConfig.isAddressEnabled()) {
            try {
                HashMap<String, Object> paramMap = new HashMap<>(16);
                paramMap.put("ip", ip);
                paramMap.put("json", true);
                String rspStr = HttpUtil.get(IP_URL, paramMap);
                if (StringUtil.isEmpty(rspStr)) {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSON.parseObject(rspStr);
                String region = obj.getString("pro");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            } catch (Exception e) {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return DEFAULT;
    }

}
